 package com.usf.jprovider.schema.provider.file.formated;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.xml.sax.SAXException;

import com.usf.jprovider.exception.XMLTagNotFundException;
import com.usf.jprovider.object.JObjectNode;
import com.usf.jprovider.object.env.Environment;
import com.usf.jprovider.object.type.JType;
import com.usf.jprovider.tools.XMLTools;

public final class XMLFile extends AbstractFormatedFileSource {

	@XmlAttribute protected String tag;
	
	public XMLFile(){
		super();
		tag = "";
	}
	public String getTag() {
		return tag;
	}

	@Override
	protected String createUnformated(Environment env, JObjectNode node) throws Exception {
		String[] values = (String[])cacheValues(env, node);
		String value = entrySelector.create(env, node, values);
		return valueSelector.create(env, node, value);
	}

	@Override
	public boolean checkValue(Environment env, JObjectNode node, JType<?> object) throws Exception {
		String[] values = (String[])cacheValues(env, node);
		int index = entrySelector.check(env, node, values, object.toString());
		return valueSelector.check(env, node, values[index], object.toString());
	}
	
	@Override
	public Object values(Environment env) throws DOMException, FileNotFoundException, 
											XMLTagNotFundException, ParserConfigurationException, SAXException, IOException  {
		return XMLTools.searchNodes(XMLTools.loadDocument(env.fullPath(path)), tag);
	}
	
	@Override
	protected String cacheIdentifier() {
		return tag + "-" + path;
	}
}
